const axios = require('axios')
import store from '@/store/login'
import {Message} from 'element-ui'

const instance = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

instance.interceptors.request.use(config => {
  config.headers = config.headers || {}
  if (config.headers && config.headers.constructor == String) {
    try {
      config.headers = JSON.parse(config.headers)
    } catch (e) {
      Message.error(`请求头部不是有效的JSON格式:${config.headers}`)
      throw e
    }
  }
  const currentUser = store.state.currentUser
  currentUser &&
    currentUser.token &&
    !config.headers.Authorization &&
    (config.headers.Authorization = `Bearer ${currentUser.token}`)
  return config
})

instance.interceptors.response.use(
  response => {
    const {data, config, headers} = response

    if (config) {
      const {responseType} = config
      // 请求的返回值类型为arraybuffer时返回headers
      if (responseType && responseType == 'arraybuffer') {
        return {data, headers}
      }
    }

    if (headers) {
      // 附件下载，需要返回 headers
      const content = headers['content-disposition']
      if (content && content.startsWith('attachment;')) {
        return {data, headers}
      }
    }

    return data
  },
  error => {
    // 处理响应失败
    const errorMessage =
      error &&
      error.response &&
      error.response.data &&
      error.response.data.message
        ? error.response.data.message
        : error.message
    if (error && error.response && error.response.status === 500) {
      if (error.response.data && error.response.data.message) {
        Message.errorLog(error.response.data.message, error.response.data.logId)
      } else if (
        error.response.config.url.indexOf(
          'dataTemplate/v1/exportByBtnSetting'
        ) != -1
      ) {
        return Promise.reject(error)
      } else {
        Message.error(error.message)
      }
    } else if (
      error &&
      error.isAxiosError &&
      error.response &&
      error.response.status != 403
    ) {
      Message.error(errorMessage)
    } else if (errorMessage && typeof errorMessage != 'undefined') {
      Message.error(errorMessage)
    }
    return Promise.reject(error)
  }
)

export default instance
